// vim:set tabstop=4 shiftwidth=4 softtabstop=4 expandtab foldcolumn=1 foldmethod=marker:
/**
 * Project:     LteERP
 * File:        src/main/DBUtil.java
 *
 * the database connection Util
 *
 * here, we use the proxool database connection pool
 * as our database connection connection tools
 *
 *  @package:   com.m5anet.main
 *  @author:    Mike.G  (hylinux@gmail.com)
 *  @license:   http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1 
 *  @copyright: http://www.5anet.com
 *  @Version: $Id: DBUtil.java 7 2008-01-10 05:01:55Z hylinux $
 *  @Date:    $Date: 2008-01-10 05:01:55 +0000 (Thu, 10 Jan 2008) $
 *
 */

package com.m5anet.main;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.*;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public final class DBUtil {

    private static DBUtil dbutil = null;
    private Logger log = null;

    /**
     * for don't let user can create the DBUtil instance by
     * its contruct
     */
    private DBUtil() {

        PropertyConfigurator.configure("common_log4j.properties");
        log = Logger.getLogger(getClass().getName());
    }

    /**
     * define one static method for create this class 
     * instance
     */
    public static DBUtil getInstance() {
        
        if ( dbutil == null ) {
            dbutil = new DBUtil();
        }

        return dbutil;
    }

    /**
     * return one database connection
     */
    public Connection getConnection() {

        DataSource ds = null;

        try {
            InitialContext initialContext = new InitialContext();
            Context context = (Context)initialContext.lookup("java:/comp/env");
            ds = (DataSource)context.lookup("jdbc/lteerp");
        } catch (Exception ex ) {
            StackTraceElement[] e = ex.getStackTrace();
            log.fatal("In Class:" + e[0].getClassName() + " ; In Method:" +
                   e[0].getMethodName() + " In Line:" +
                    e[0].getLineNumber() + "; In File:" + e[0].getFileName() +
                    " we got a fata error " + ex.getMessage() );
            log.fatal(" here is the trace tree:" );
            ex.printStackTrace();
        }

        Connection connection = null;

        try {
            connection = ds.getConnection();
        } catch (SQLException ex ) {
            StackTraceElement[] e = ex.getStackTrace();
            log.fatal("In Class:" + e[0].getClassName() + " ; In Method:" +
                   e[0].getMethodName() + " In Line:" +
                    e[0].getLineNumber() + "; In File:" + e[0].getFileName() +
                    " we got a fata error " + ex.getMessage() );
            log.fatal(" here is the trace tree:" );
            ex.printStackTrace();

        }

        return connection;
    }
}
